package com.qiguliuxing.dts.core.notify;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaTemplateData;
import cn.binarywang.wx.miniapp.bean.WxMaTemplateMessage;
import cn.binarywang.wx.miniapp.constant.WxMaConstants;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.qiguliuxing.dts.db.domain.DtsUserFormid;
import com.qiguliuxing.dts.db.service.DtsUserFormIdService;
import me.chanjar.weixin.common.error.WxError;
import me.chanjar.weixin.common.error.WxErrorException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.List;

/**
 * 微信模版消息通知
 */
public class WxTemplateSender {
    private final Log logger = LogFactory.getLog(WxTemplateSender.class);

    @Autowired
    private WxMaService wxMaService;

    @Autowired
    private DtsUserFormIdService formIdService;

    /**
     * 发送微信消息(模板消息),不带跳转
     *
     * @param touser    用户 OpenID
     * @param templatId 模板消息ID
     * @param parms     详细内容
     */
    public void sendWechatMsg(String touser, String templatId, List<WxMaTemplateData> parms) {
        sendMsg(touser, templatId, parms, "/pages/index/index", "", "");
    }

    /**
     * 发送微信消息(模板消息),带跳转
     *
     * @param touser    用户 OpenID
     * @param templatId 模板消息ID
     * @param parms     详细内容
     * @param page      跳转页面
     */
    public void sendWechatMsg(String touser, String templatId, List<WxMaTemplateData> parms, String page) {
        sendMsg(touser, templatId, parms, page, "", "");
    }

    private void sendMsg(String touser, String templatId, List<WxMaTemplateData> parms, String page, String color,
                         String emphasisKeyword) {
        logger.info("【微信通知】sendMsg-> begin ....touser:{}" + touser);
        DtsUserFormid userFormid = formIdService.queryByOpenId(touser);
        if (userFormid == null) {
            logger.error("【微信通知】sendMsg-> error .... touser:{}" + touser);
            return;
        }
        WxMaTemplateMessage msg = new WxMaTemplateMessage();
        msg.setTemplateId(templatId);
        msg.setToUser(touser);
        msg.setFormId(userFormid.getFormid());
        msg.setPage(page);
        msg.setColor(color);
        msg.setEmphasisKeyword(emphasisKeyword);
        msg.setData(parms);

        try {
            this.sendTemplateMsg(msg);
            if (formIdService.updateUserFormId(userFormid) == 0) {
                logger.warn("更新数据已失效");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        logger.info("【微信通知】sendMsg-> end ....");
    }

    String TEMPLATE_MSG_SEND_URL = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send";

    public void sendTemplateMsg(WxMaTemplateMessage templateMessage) throws WxErrorException {
        logger.info("【微信通知】sendTemplateMsg -> begin ....");
        String responseContent = this.wxMaService.post(TEMPLATE_MSG_SEND_URL, templateMessage.toJson());
        JSONObject jsonObject = JSON.parseObject(responseContent);
        logger.info("【微信通知】sendTemplateMsg -> end ....responseContent:{}" + responseContent);
        if ((Integer) jsonObject.get(WxMaConstants.ERRCODE) != 0) {
            throw new WxErrorException(WxError.fromJson(responseContent));
        }
    }

    private List<WxMaTemplateData> createMsgData(String[] parms) {
        List<WxMaTemplateData> dataList = new ArrayList<WxMaTemplateData>();
        for (int i = 1; i <= parms.length; i++) {
            dataList.add(new WxMaTemplateData("keyword" + i, parms[i - 1]));
        }

        return dataList;
    }
}
